package com.sihai.ehr.web.action.salary;

import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.SalaryCustom;
import com.sihai.ehr.model.biz.SalaryCustomDetail;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.SalaryFrameworkEnum;
import com.sihai.ehr.model.sys.SalaryStructureEnum;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.SalaryCustomService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 薪资结构控制器
 * 
 * @author henry
 * 
 */
@Results({ @Result(name = "main", location = "salary_main.jsp"), @Result(name = "custom_manage", location = "custom_manage.jsp"),
		@Result(name = "list", location = "custom_manage_list.jsp") })
public class CustomStructAction extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2106672426606254873L;

	private Log log = LogFactory.getLog(CustomStructAction.class);

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private SalaryCustomService salaryCustomService;

	private List<Organization> organizations;

	private SalaryCustom custom;
	private LimitedList<SalaryCustom> customs;
	private Long customId;
	private String ids;

	// 补贴项目数
	private int subsidyItemLength = 0;
	// 扣款项目数
	private int detainItemLength = 0;

	@Action("/salary/custom_main")
	@Override
	public String execute() throws Exception {
		listTitle = "自定义薪资架构管理";
		listAction = "/salary/custom_list.xhtml";
		organizations = organizationService.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		return "main";
	}

	@Action("/salary/custom_list")
	public String list() {
		listAction = "/salary/custom_list.xhtml";
		customs = salaryCustomService.find(organizationId, createLimit(), createSorter());
		paging(customs);
		setPageUrl("salary/custom_list.xhtml");
		return "list";
	}

	@Action("/salary/custom_manage")
	public String dispatchInsurance() throws Exception {
		if (customId == null || customId < 0) { // 添加
			custom = new SalaryCustom();
			custom.setOrganization(organizationService.get(organizationId));
		} else { // 修改
			custom = salaryCustomService.get(customId);
			if (custom.getDetails() != null && custom.getDetails().size() > 0) {
				for (Iterator iterator = custom.getDetails().iterator(); iterator.hasNext();) {
					SalaryCustomDetail type = (SalaryCustomDetail) iterator.next();
					if (type.getStructType() == SalaryStructureEnum.subsidy) {
						subsidyItemLength++;
					} else {
						detainItemLength++;
					}

				}
			}
		}
		return "custom_manage";
	}

	@Action("/salary/post_custom")
	public String postCustom() throws Exception {
		if (custom == null) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}

		if (custom.getId() == null) {
			// 添加
		} else {
			// 修改
			/**
			 * 删除方案项目细节
			 */
			salaryCustomService.deleteCustomDetails(custom.getId());
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		if (custom.getPaymentType() == 0) {
			// 单次发放
			custom.setStartDate(formatter.parse(getParameter("singlePaymentDate")));
		} else {
			custom.setStartDate(formatter.parse(getParameter("startDate")));
			custom.setEndDate(formatter.parse(getParameter("endDate")));
		}

		Set<SalaryCustomDetail> details = new HashSet<SalaryCustomDetail>();
		// subsidy
		String[] schemeTitle_subsidy = getParameterValues("schemeTitle_subsidy");
		String[] linkedDataType_subsidy = getParameterValues("linkedDataType_subsidy");
		String[] linkedDataId_subsidy = getParameterValues("linkedDataId_subsidy");
		String[] linkedDataTitle_subsidy = getParameterValues("linkedDataTitle_subsidy");
		String[] unitCost_subsidy = getParameterValues("unitCost_subsidy");
		String[] fixedCost_subsidy = getParameterValues("fixedCost_subsidy");

		// detain
		String[] schemeTitle_detain = getParameterValues("schemeTitle_detain");
		String[] linkedDataType_detain = getParameterValues("linkedDataType_detain");
		String[] linkedDataId_detain = getParameterValues("linkedDataId_detain");
		String[] linkedDataTitle_detain = getParameterValues("linkedDataTitle_detain");
		String[] unitCost_detain = getParameterValues("unitCost_detain");
		String[] fixedCost_detain = getParameterValues("fixedCost_detain");

		if (schemeTitle_subsidy != null && schemeTitle_subsidy.length > 0) {
			for (int i = 0; i < schemeTitle_subsidy.length; i++) {
				SalaryCustomDetail detail = new SalaryCustomDetail();
				detail.setSchemeTitle(schemeTitle_subsidy[i]);
				detail.setLinkedDataType(SalaryFrameworkEnum.valueOf(linkedDataType_subsidy[i]));
				detail.setLinkedDataId(Long.parseLong(linkedDataId_subsidy[i]));
				detail.setLinkedDataTitle(linkedDataTitle_subsidy[i]);
				detail.setUnitCost(unitCost_subsidy[i] == null || unitCost_subsidy[i].trim().isEmpty() ? 0F : Float.parseFloat(unitCost_subsidy[i]));
				detail.setFixedCost(fixedCost_subsidy[i] == null || fixedCost_subsidy[i].trim().isEmpty() ? 0F : Float.parseFloat(fixedCost_subsidy[i]));
				detail.setStructType(SalaryStructureEnum.subsidy);
				custom.addDetailItem(detail);
			}
		}

		if (schemeTitle_detain != null && schemeTitle_detain.length > 0) {
			for (int i = 0; i < schemeTitle_detain.length; i++) {
				SalaryCustomDetail detail = new SalaryCustomDetail();
				detail.setSchemeTitle(schemeTitle_detain[i]);
				detail.setLinkedDataType(SalaryFrameworkEnum.valueOf(linkedDataType_detain[i]));
				detail.setLinkedDataId(Long.parseLong(linkedDataId_detain[i]));
				detail.setLinkedDataTitle(linkedDataTitle_detain[i]);
				detail.setUnitCost(unitCost_detain[i] == null || unitCost_detain[i].trim().isEmpty() ? 0F : Float.parseFloat(unitCost_detain[i]));
				detail.setFixedCost(fixedCost_detain[i] == null || fixedCost_detain[i].trim().isEmpty() ? 0F : Float.parseFloat(fixedCost_detain[i]));
				detail.setStructType(SalaryStructureEnum.detain);
				custom.addDetailItem(detail);
			}
		}
		// 保存数据
		try {
			salaryCustomService.save(custom);
		} catch (Exception e) {
			log.equals(e.getMessage());
			return ERROR;
		}
		return "main";
	}

	/**
	 * 删除自定义方案
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/salary/custom_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteCustomStruct() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				salaryCustomService.deleteCustoms(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}

		}

		return SUCCESS;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public SalaryCustom getCustom() {
		return custom;
	}

	public void setCustom(SalaryCustom custom) {
		this.custom = custom;
	}

	public LimitedList<SalaryCustom> getCustoms() {
		return customs;
	}

	public void setCustoms(LimitedList<SalaryCustom> customs) {
		this.customs = customs;
	}

	public Long getCustomId() {
		return customId;
	}

	public void setCustomId(Long customId) {
		this.customId = customId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public int getSubsidyItemLength() {
		return subsidyItemLength;
	}

	public void setSubsidyItemLength(int subsidyItemLength) {
		this.subsidyItemLength = subsidyItemLength;
	}

	public int getDetainItemLength() {
		return detainItemLength;
	}

	public void setDetainItemLength(int detainItemLength) {
		this.detainItemLength = detainItemLength;
	}
}
